<script setup>

import {Calendar, Search} from "@element-plus/icons-vue";
import {ref,reactive} from "vue";

import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";


// 导入相关
const importVisible = ref(false);
const importFile = ref(null);
const importFormRef = ref();

// 打开导入弹窗
const handleImport = () => {
  importVisible.value = true;
};

// 上传文件前的校验
const beforeUpload = (file) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
  if (!isExcel) {
    ElMessage.error('仅支持上传Excel文件');
    return false;
  }
  return true;
};

// 上传成功处理
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    ElMessage.success('导入成功');
    load(); // 刷新表格
    importVisible.value = false;
  } else {
    ElMessage.error(res.msg);
  }
};

// 导出Excel
const handleExport = () => {
  request.get('/admin/export', {
    responseType: 'blob' // 关键：指定响应为二进制流
  }).then(res => {
    // 创建Blob对象并生成下载链接
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '管理员数据.xlsx'; // 下载文件名
    link.click();
    window.URL.revokeObjectURL(url); // 释放内存
    ElMessage.success('导出成功');
  }).catch(error => {
    ElMessage.error('导出失败');
  });
};


const data = reactive({
  name: null,
  total: 0,
  pageNum: 1,
  pageSize: 5,
  tableData: [],
  username: null,
  FormVisible: false,
  form: {},
  rules: {
    username: [
      {required: true, message: '请填写账号', trigger: 'blur'}
    ],
    password: [
      {required: true, message: '请填写密码', trigger: 'blur'}
    ],
    name: [
      {required: true, message: '请填写账名称', trigger: 'blur'}
    ],
    phone: [
      {required: true, message: '请填写电话号码', trigger: 'blur'}
    ],
    email: [
      {required: true, message: '请填写邮箱', trigger: 'blur'}
    ]

  },
  rows: []

})
const formRef = ref()

const load = () => {
  request.get('admin/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      username: data.username
    }

  }).then(res => {
    console.log(res)
    data.tableData = res.data.list
    data.total = res.data.total

  })
}

load()

const reset = () => {
  data.name = null
  data.username = null
  load()
}

reset()


const handleadd = () => {
  data.FormVisible = true
  data.form = {}

}

const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post("/admin/add", data.form).then(res => {

        if (res.code === '200') {
          data.FormVisible = false
          ElMessage.success("添加成功");
          load()

        } else {
          ElMessage.error(res.msg);

        }
      })
    }
  })

}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.FormVisible = true

}

const update = () => {
  request.put('admin/update', data.form).then(res => {
    if (res.code === '200') {
      data.FormVisible = false
      ElMessage.success("更新成功");
      load()

    } else {
      ElMessage.error(res.msg);

    }
  })
}

const save = () => {
  data.form.id ? update() : add()
}


const del = (id) => {
  ElMessageBox.confirm(
      '你要确认删除该行数据吗？确认删除后，该数据无法恢复!!!!',
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
  )
      .then(res => {
        request.delete('/admin/delete/' + id).then(res => {
          if (res.code === '200') {
            data.FormVisible = false
            ElMessage.success("删除成功");
            load()

          } else {
            ElMessage.error(res.msg);

          }

        })


      })
      .catch(error => {

      })

}

const handleSelectionChange = (rows) => {
  data.rows = rows
}

const deleteBatch = () => {

  if (data.rows.length === 0) {
    ElMessage.error("请选择需要删除的数据...")
  } else {
    ElMessageBox.confirm(
        '你要确认删除选中的数据吗？确认删除后，该数据无法恢复!!!!',
        '删除确认',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
        }
    )
        .then(res => {
          request.delete('/admin/deleteBatch', {data: data.rows}).then(res => {
            if (res.code === '200') {
              data.FormVisible = false
              ElMessage.success("删除成功");
              load()
            } else {
              ElMessage.error(res.msg);

            }

          })


        })
        .catch(error => {

        })

  }


}


</script>

<template>

  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear='load' style="width: 260px; margin-right: 5px" v-model="data.name"
                placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
      <el-input clearable @clear='load' style="width: 260px; margin-right: 5px" v-model="data.username"
                placeholder="请输入用户名查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="primary" @click="reset">重置</el-button>

    </div>

    <div class="card" style="margin-bottom: 5px">
      <!--      <el-button type="danger" @click="handleadd">新增</el-button>-->
      <!-- Form -->
      <el-button @click="handleadd" type="danger">新增</el-button>
      <el-button type="primary" @click="deleteBatch">批量删除</el-button>
      <el-button type="warning" @click="handleImport">批量导入</el-button>
      <el-button type="info" @click="handleExport">批量导出</el-button>
    </div>


    <div>
      <div class="card" style="margin-bottom: 5px">
        <el-table :data="data.tableData" stripe style="width: 100%"
                  :header-cell-style="{color: '#333', backgroundColor: '#ddd'}"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="username" label="账号"/>
          <el-table-column prop="password" label="用户密码"/>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="phone" label="电话号码"/>
          <el-table-column prop="email" label="邮箱"/>
          <el-table-column label="修改/删除" width="100">
            <template #default="scope">
              <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
              <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
            </template>

          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="card">

      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-size="data.pageSize"
          :page-sizes="[5,10,20]"
          :pager-count="11"
          background layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          @current-change="load"
          @size-change="load"

      />
    </div>

    <el-dialog v-model="data.FormVisible" title="新增管理员" center destroy-on-close width=40%>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px" style="padding: 0px 20px 0 30px">
        <el-form-item label="账户名" prop="username">
          <el-input v-model="data.form.username" autocomplete="off"/>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="data.form.password" autocomplete="off"/>
        </el-form-item>

        <el-form-item label="用户名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off"/>
        </el-form-item>

        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="data.form.phone" autocomplete="off"/>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.form.email" autocomplete="off"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary">Create</el-button>
          <el-button>Cancel</el-button>
        </el-form-item>

      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.FormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </span>
      </template>
    </el-dialog>

    <div>
      <!-- 批量导入按钮 -->
      <el-button type="warning" @click="handleImport">批量导入</el-button>

      <!-- 导入弹窗 -->
      <el-dialog v-model="importVisible" title="批量导入" width="30%">
        <el-upload
            class="upload-demo"
            action="http://localhost:8080/admin/import"
            :headers="headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :show-file-list="false"
            accept=".xlsx, .xls"
        >
          <el-button type="primary">点击上传Excel文件</el-button>
          <template #tip>
            <div class="el-upload__tip">仅支持 .xlsx/.xls 格式文件</div>
          </template>
        </el-upload>
        <template #footer>
          <el-button @click="importVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>

  </div>

</template>


<style scoped>

</style>